<template>
	<div class="app-container">
		<el-tabs v-model="selectedName" class="demo-tabs" @tab-click="tabClick">
    		<el-tab-pane label="建筑物公里格网" name="first">
				<el-radio-group v-model="radio" style="margin-bottom: 14px;" @tab-click="changeRadio" type="card">
					<el-radio label="0">国家级数据</el-radio>
					<el-radio label="1">自定义类-完全版</el-radio>
					<el-radio label="2">自定义类群体版</el-radio>
					<el-radio label="3">自定义类-国家级数据生成版</el-radio>
				</el-radio-group>

				<el-form :model="queryParams" ref="queryRef" :inline="true" label-width="160px">
					<el-row>
						<el-col :span="8">
							<el-form-item label="省" prop="provinceId">
								<el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable
									:disabled="isProvince">
									<el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="市" prop="cityId">
								<el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable :disabled="isCity">
									<el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="区/县" prop="countyId">
								<el-select v-model="queryParams.countyId" placeholder="请选择区/县" @change="chooseCounty" clearable
									:disabled="isCounty">
									<el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="结构类型" prop="structureType1">
								<el-select v-model="queryParams.structureType1" placeholder="请选择" @change="structureTypeChange" clearable>
									<el-option v-for="item in structureTypeOptions" :key="item.value" :label="item.label" :value="item.value">
									</el-option>
								</el-select>
								&nbsp;—&nbsp;
								<el-select v-model="queryParams.structureType2" placeholder="请选择" clearable>
									<el-option v-for="item in structureType1Options" :key="item.value" :label="item.label" :value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="设防情况" prop="fortify">
								<el-select v-model="queryParams.fortify" placeholder="请选择">
									<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="radio == '0' || radio == '1'">
							<el-form-item label="年代" prop="year">
								<el-select v-model="queryParams.year" placeholder="请选择">
									<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label" :value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="radio == '0' || radio == '1'">
							<el-form-item label="用途" prop="housingUse1">
								<el-select v-model="queryParams.housingUse1" placeholder="请选择" clearable @change="useChange">
									<el-option v-for="item in useOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
								</el-select>
								&nbsp;—&nbsp;
								<el-select v-model="queryParams.housingUse2" placeholder="请选择" clearable>
									<el-option v-for="item in useOptions1" :key="item.value" :label="item.label" :value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="radio == '0' || radio == '1'">
							<el-form-item label="层数" prop="numberOfFloors">
								<el-select v-model="queryParams.numberOfFloors" placeholder="请选择" class="form-select" clearable :disabled="disabledcs">
									<el-option v-for="item in csOptions" :key="item.value" :label="item.label" :value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="维护人" prop="userName">
								<el-input v-model="queryParams.userName" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="维护时间" prop="startTime">
								<el-date-picker clearable v-model="queryParams.startTime" type="date" placeholder="开始时间"
									value-format="YYYY-MM-DD" :disabled-date="startDisableDate" style="width: 190px;" />
								&nbsp;—&nbsp;
								<el-date-picker clearable v-model="queryParams.endTime" type="date" placeholder="结束时间"
									value-format="YYYY-MM-DD" :disabled-date="endDisableDate" style="width: 190px;" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-form-item label=" ">
							<el-button type="primary" @click="getList">查询</el-button>
							<el-button plain @click="resetQuery">重置</el-button>
							<el-button type="primary" icon="Download" @click="importExcel" v-if="radio == '1' || radio == '2'">导入</el-button>
							<el-button type="primary" @click="creatOpen" v-if="radio == '3'">生成</el-button>
						</el-form-item>
					</el-row>
				</el-form>
				<!-- 导入 -->
				<ExcelImport v-model:open="importOpen" :uploadParams="uploadParams" @importSuccess="importSuccess"
					@importCover="importCover" :coverData="true" />

				<el-divider></el-divider>

				<el-table v-loading="loading" :data="dataList" stripe>
					<el-table-column prop="number" header-align="center" align="center" label="编号" width="180" v-if="radio == '0'">
						<template #default="{ row }">
							<el-button link type="text" @click.prevent="onClickNumber(row)">{{ row.number }}</el-button>
						</template>
					</el-table-column>
					<el-table-column prop="number" header-align="center" align="center" label="序号" width="55" v-else>
						<template #default="{ row, $index }">
							<el-button link type="text" @click.prevent="onClickNumber(row)">{{ (queryParams.page - 1) * queryParams.rows + $index + 1 }}</el-button>
						</template>
					</el-table-column>
					<el-table-column label="省" align="center" prop="province" />
					<el-table-column label="市" align="center" prop="city" />
					<el-table-column label="区/县" align="center" prop="county" />
					<el-table-column label="结构类型" align="center" prop="structureType">
						<template #default="{ row }">
							<span>{{ row.structureType }}{{ row.structureType1 ? `/${row.structureType1}` : '' }}</span>
						</template>
					</el-table-column>
					<el-table-column label="房屋用途" align="center" prop="housingUse1" v-if="radio == '0' || radio == '1'">
						<template #default="{ row }">
							<span>{{ row.use0 }}{{ row.use1 ? `/${row.use1}` : '' }}</span>
						</template>
					</el-table-column>
					<el-table-column label="设防情况" align="center" prop="fortification" />
					<el-table-column label="年代" align="center" prop="years" v-if="radio == '0' || radio == '1'" />
					<!-- <el-table-column label="破坏程度" align="center" prop="dataType" v-if="radio=='0'||radio=='1'" /> -->
					<el-table-column label="层数" align="center" prop="numberOfFloors" v-if="radio == '0' || radio == '1'" />
					<el-table-column header-align="center" align="center" label="维护时间" width="180">
						<template #default="{ row }">
							<span v-if="row.createTime && row.createTime.includes('.')">{{ row.createTime.split('.')[0] }}</span>
							<span v-if="row.createTime && !row.createTime.includes('.')">{{ row.createTime }}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
						<template #default="scope">
							<el-button type="text" @click="handleUpdate(scope.row)">修改</el-button>
						</template>
					</el-table-column>
				</el-table>

				<pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
					v-model:limit="queryParams.rows" @pagination="getList" />

				<el-collapse-transition>
					<div v-show="showMatrix">
						<hr style="margin-top: 18px;" />
						<el-row justify="end" class="table-matrix" v-if="radio == '0'">
							<el-button type="primary" @click="exportMatrixTableData">导出易损性矩阵</el-button>
						</el-row>
						<h4>地震易损性矩阵</h4>
						<el-table class="listTables headborder-table" id="tableRef" ref="tableRef" border :data="tableDataMatrix" style="width: 100%"
							:cell-style="{ border: '1px solid #e5ebf7' }"
							:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }" v-loading="matrixLoading">
							<el-table-column prop="damage" label="破坏程度" align="right" width="150">
								<el-table-column prop="intensity" label="烈度" width="150" align="center"></el-table-column>
							</el-table-column>
							<el-table-column header-align="center" align="center" label="基本完好" prop="intensity1">
								<template #default="scope">{{ scope.row.intensity1 }}</template>
							</el-table-column>
							<el-table-column header-align="center" align="center" label="轻微破坏" prop="sl">
								<template #default="scope">{{ scope.row.intensity2 }}</template>
							</el-table-column>
							<el-table-column header-align="center" align="center" label="中等破坏" prop="ml">
								<template #default="scope">{{ scope.row.intensity3 }}</template>
							</el-table-column>
							<el-table-column header-align="center" align="center" label="严重破坏" prop="el">
								<template #default="scope">{{ scope.row.intensity4 }}</template>
							</el-table-column>
							<el-table-column header-align="center" align="center" label="倒塌" prop="c">
								<template #default="scope">{{ scope.row.intensity5 }}</template>
							</el-table-column>
						</el-table>
					</div>
				</el-collapse-transition>

				<el-dialog v-model="showMatrixDialog" title="修改易损性矩阵" width="500" append-to-body>
					<h4>地震易损性矩阵</h4>
						<el-form ref="buildVulnerabilityRef" :model="form" :rules="rules" >
							<el-table class="listTables headborder-table" id="tableRef" ref="tableRef" border :data="form.tableDataMatrix" style="width: 100%"
								:cell-style="{ border: '1px solid #e5ebf7' }"
								:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }" v-loading="matrixLoading">
								<el-table-column prop="damage" label="破坏程度" align="right" width="150">
									<el-table-column prop="intensity" label="烈度" width="150" align="center"></el-table-column>
								</el-table-column>
								<el-table-column header-align="center" align="center" label="基本完好" prop="one">
									<template #default="scope">
										<el-form-item :prop="'tableDataMatrix.' + scope.$index + '.one'" :rules="rules.one">
											<el-input v-model="scope.row.one">
												<template #suffix>%</template>
											</el-input>
										</el-form-item>
									</template>
								</el-table-column>
								<el-table-column header-align="center" align="center" label="轻微破坏" prop="two">
									<template #default="scope">
										<el-form-item :prop="'tableDataMatrix.' + scope.$index + '.two'" :rules="rules.two">
											<el-input v-model="scope.row.two">
												<template #suffix>%</template>
											</el-input>
										</el-form-item>
									</template>
								</el-table-column>
								<el-table-column header-align="center" align="center" label="中等破坏" prop="three">
									<template #default="scope">
										<el-form-item :prop="'tableDataMatrix.' + scope.$index + '.three'" :rules="rules.three">
											<el-input v-model="scope.row.three">
												<template #suffix>%</template>
											</el-input>
										</el-form-item>
									</template>
								</el-table-column>
								<el-table-column header-align="center" align="center" label="严重破坏" prop="four">
									<template #default="scope">
										<el-form-item :prop="'tableDataMatrix.' + scope.$index + '.four'" :rules="rules.four">
											<el-input v-model="scope.row.four">
												<template #suffix>%</template>
											</el-input>
										</el-form-item>
									</template>
								</el-table-column>
								<el-table-column header-align="center" align="center" label="倒塌" prop="fiv">
									<template #default="scope">
										<el-form-item :prop="'tableDataMatrix.' + scope.$index + '.fiv'" :rules="rules.fiv">
											<el-input v-model="scope.row.fiv">
												<template #suffix>%</template>
											</el-input>
										</el-form-item>
									</template>
								</el-table-column>
							</el-table>
						</el-form>
  				  <template #footer>
  				    <div class="dialog-footer">
						<el-button type="primary" @click="updateForm" auto-insert-space>保存</el-button>
						<el-button plain @click="showMatrixDialog=false" auto-insert-space>取消</el-button>
  				    </div>
  				  </template>
  				</el-dialog>

				<CreateData ref="creatDataRef" v-model:open="openCreat" :fortifyOptions="fortificationOptions" @createSuccess="createSuccess"
					:roleObj="roleObj" :provinceData="provinceData" v-if="provinceData.length > 0 && JSON.stringify(roleObj) != '{}'" />
			</el-tab-pane>
			<el-tab-pane label="建筑物单体" name="secend">
				<keilometer v-if="selectedName=='secend'" />
			</el-tab-pane>
  		</el-tabs>
	</div>
</template>
<script setup>
import { getPage, customGenerateApi, getRole,updateList } from '@/api/basicDataManage/ysxData'
import { getProvince, getChildArea } from "@/api/system/division"
import keilometer from './kilometer.vue'
// 引入导入弹框
import ExcelImport from '@/components/ExcelImport'
// 引入生成弹框
import CreateData from './CreateData.vue'
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
// 前端导出excel文件
import { export_json_to_excel } from '@/vendor/Export2Excel';
// 状态管理模块
import useDictStore from "@/store/modules/dict";
const dictStore = useDictStore();

// 当前实例
const { proxy } = getCurrentInstance()
// 保留两位小数
const positive2decimals = (rule, value, callback) => {
    if (value) {
        value = String(value)
    }
    if (!value) {
        callback(new Error())
    } else if (value.split('.').length > 2) {
        callback(new Error()) //防止输入多个小数点
    } else {
        callback();
    }
}
// 变量
const queryData = reactive({
	radio: '0',
	queryParams: {
		page: 1,
		rows: 10,
		roleType: '0',
	},
	total: 0,
	loading: false,
	dataList: [],
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	// 年代
	yearsOptions: dictStore.yearsOptions || [],
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 用途
	useOptions: dictStore.useOptions || [],
	useOptions1: [],
	// 层数
	csOptions: dictStore.csOptions || [],
	// 表格
	tableData: [],
	tableDataMatrix: [],
	curRow: {},
	rules:{
		one: [
			{ required: true, message: '请输入', trigger: ['blur','change'] },
			{ pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字且最多两位小数', trigger: 'blur' }
		],
		two: [
			{ required: true, message: '请输入', trigger: ['blur','change'] },
			{ pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字且最多两位小数', trigger: 'blur' }
		],
		three: [
			{ required: true, message: '请输入', trigger: ['blur','change'] },
			{ pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字且最多两位小数', trigger: 'blur' }
		],
		four: [
			{ required: true, message: '请输入', trigger: ['blur','change'] },
			{ pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字且最多两位小数', trigger: 'blur' }
		],
		fiv: [
			{ required: true, message: '请输入', trigger: ['blur','change'] },
			{ pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字且最多两位小数', trigger: 'blur' }
		],
	}
})
const { queryParams, total, loading, dataList, radio, structureTypeOptions, structureType1Options, yearsOptions, fortificationOptions, useOptions, useOptions1, csOptions, tableData, tableDataMatrix, curRow,rules } = toRefs(queryData)

// 省市县
const provinceData = ref([])
const cityData = ref([])
const areaData = ref([])

// 切换单选
const changeRadio = (value) => {
	radio.value = value
	proxy.resetForm('queryRef')
	queryParams.value.provinceId = isProvince.value ? roleObj.value.provinceId : '';
	queryParams.value.cityId = isCity.value ? roleObj.value.cityId : '';
	queryParams.value.countyId = isCounty.value ? roleObj.value.countyId : '';
	if (!isProvince.value) queryParams.value.province = '';
	if (!isCity.value) queryParams.value.city = '';
	if (!isCounty.value) queryParams.value.county = '';
	queryParams.value.structureType2 = ''
	queryParams.value.housingUse2 = ''
	queryParams.value.endTime = ''
	showMatrix.value = false;
	tableDataMatrix.value = []
	dataList.value = [];
	total.value = 0;
	getAdmin()
	// getList()
}

// 以下结构对应全楼层
const arrStructure = ['钢筋混凝土结构', '钢结构', '组合结构'];

// 选择结构类型
const disabledcs = ref(false);
const structureTypeChange = (val) => {
  const structureTypes = structureTypeOptions.value.find(
    (item) => item.value === val
  );
  if (structureTypes) {
    structureType1Options.value = structureTypes.children;
  }
  queryParams.value.structureType2 = ''; // 切换一级下拉，置空二级下拉
	// 清空用途
	queryParams.value.housingUse1 = '';
	queryParams.value.housingUse2 = '';
	useOptions1.value = [];
	// 设防情况
	queryParams.value.fortify = '';
	fortificationOptions.value = dictStore.fortificationOptions;
	// 年代
	yearsOptions.value = dictStore.yearsOptions;
	// 过滤楼层预选项
	if (val=='钢筋混凝土结构'||val=='钢结构') {
		csOptions.value = dictStore.csOptions;
		disabledcs.value = false;
		// 用途处理
		useOptions.value = dictStore.useOptions;
	} else if(val=='组合结构'){
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index == 2);
		queryParams.value.numberOfFloors = ''
		disabledcs.value = false;
		// 用途处理
		useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '公寓',
                        label: '公寓'
                    },
                    {
                        value: '学生和职工集体宿舍',
                        label: '学生和职工集体宿舍'
                    },
                    {
                        value: '宾馆',
                        label: '宾馆'
                    },
                    {
                        value: '招待所',
                        label: '招待所'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '办公室',
                        label: '办公室'
                    },
                ]
            },
        ]
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value!='未设防'&&item.value!='自设防'));
	}else if(val=='砌体结构'){
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index < 2);
		disabledcs.value = false;
		// 切换类型时，部分类型楼层没有就"9层以上"选项，则清空
		if (queryParams.value.numberOfFloors == '9层以上') {
			queryParams.value.numberOfFloors = ''
		}
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions;
	}else{
		// 层数处理
		disabledcs.value = true;
		csOptions.value = [];
		queryParams.value.numberOfFloors = ''
		// 用途
		if(val=='土木结构'||val=='木结构'||val=='其他'){
			useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅲ类',
                label: '第Ⅲ类',
                children: [
                    {
                        value: '除I、II类以外',
                        label: '除I、II类以外'
                    }
                ]
            }
        ]
		if(val=='土木结构'){
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>item.value=='未设防');
		yearsOptions.value = dictStore.yearsOptions.filter((item, index) => index < 4);
		// 切换类型时，年代--选项，则清空
		if (queryParams.value.year == '2010-2016年'||queryParams.value.year == '2016年以后') {
			queryParams.value.year = ''
		}
		}else if(val=='其他'){
			fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value=='未设防'||item.value=='自设防'||item.value=='6度'));
		}
	}else{
			useOptions.value = [
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '生产车间',
                        label: '生产车间'
                    },
                ]
            },
        ]
		}
	}
};
// 选择用途
const useChange = (val) => {
  const use = useOptions.value.find((item) => item.value === val);
  if (use) {
    queryParams.value.housingUse2 = ''; // 切换一级下拉，置空二级下拉
    useOptions1.value = use.children;
  }
};

// 显示矩阵
let showMatrix = ref(false);
const tableRef = ref()
let matrixLoading = ref(false);
// 点击编号，展示导入的易损性矩阵或曲线
function onClickNumber(row) {
	let query = {}
	if (radio.value == '0') {
		query = { id: row.pid, dataType: row.dataType, ysxType: radio.value, province:row.province }
	} else {
		query = { id: row.id, ysxType: radio.value, province:row.province }
	}
	matrixLoading.value = true
	customGenerateApi(query).then(res => {
		const { data, code } = res;
		if (code == 200 && data) {
			// 显示矩阵
			showMatrix.value = true;
			// 设置矩阵数据
			setMatrixData(data.rows);
			matrixLoading.value = false

			let timer = setTimeout(() => {
				tableRef.value.$el.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest"  });
				clearTimeout(timer)
			}, 500);
		}
	})
}

const showMatrixDialog = ref(false);
const form = ref({
	tableDataMatrix:[]
})
const messageArr = ref([])
function handleUpdate(row){
	let query = {}
	if (radio.value == '0') {
		query = { id: row.pid, dataType: row.dataType, ysxType: radio.value, province:row.province }
	} else {
		query = { id: row.id, ysxType: radio.value, province:row.province }
	}
	matrixLoading.value = true
	customGenerateApi(query).then(res => {
		const { data, code } = res;
		if (code == 200 && data) {
			// 显示矩阵
			showMatrixDialog.value = true;
			// 设置矩阵数据
			setMatrixData(data.rows);
			matrixLoading.value = false
			form.value.tableDataMatrix = tableDataMatrix.value;
			console.log(form.value.tableDataMatrix,'lalall');
			let timer = setTimeout(() => {
				tableRef.value.$el.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest"  });
				clearTimeout(timer)
			}, 500);
		}
	})
}
function updateForm(){
    proxy.$refs["buildVulnerabilityRef"].validate(valid => {
        if (valid) {
            checkradio();
			console.log(messageArr.value.length,'??');
            if (messageArr.value.length > 0) {
                const msg = messageArr.value.join('<br/><br/>')
                ElMessage({
                    message: msg,
                    type: 'error',
                    dangerouslyUseHTMLString: true,
                })
            } else {
				console.log('打印');
                let list = []
				form.value.tableDataMatrix.forEach((item)=>{
					list = [
						...list,
						...[{intensity:item.intensity,damage:item.damageBs,rate:item.one+'%',pid:item.pid},
						{intensity:item.intensity,damage:item.damageSl,rate:item.two+'%',pid:item.pid},
						{intensity:item.intensity,damage:item.damageMl,rate:item.three+'%',pid:item.pid},
						{intensity:item.intensity,damage:item.damageEl,rate:item.four+'%',pid:item.pid},
						{intensity:item.intensity,damage:item.damageC,rate:item.fiv+'%',pid:item.pid}]
					]
				})
				console.log(list,'xixixix');
                updateList(list).then(response => {
                    proxy.$modal.msgSuccess("保存成功");
                    showMatrixDialog.value = false;
                    getList();
                }).catch(err=>{
                });
            }
        }
    });
}
// 防止精度不准确
function precision(num, precise) {
    return parseFloat(num.toPrecision(precise));
}

// 校验表单项目比例
function checkradio() {
    messageArr.value = [];
    let one = precisionTotal(0);
    let two = precisionTotal(1);
    let three = precisionTotal(2);
    let four = precisionTotal(3);
    let five = precisionTotal(4);
    let six = precisionTotal(5);
	console.log(one,two,three);
    
    if (precision(one, 3) != 100||precision(one, 3) != 100.0||precision(one, 3) != 100.00) {
        messageArr.value.push('5度的破坏占比不为100')
    }
    if (precision(two, 3) != 100||precision(two, 3) != 100.0||precision(two, 3) != 100.00) {
        messageArr.value.push('6度的破坏占比不为100')
    }
    if (precision(three, 3) != 100||precision(three, 3) != 100.0||precision(three, 3) != 100.00) {
        messageArr.value.push('7度的破坏占比不为100')
    }
    if (precision(four, 3) != 100||precision(four, 3) != 100.0||precision(four, 3) != 100.00) {
        messageArr.value.push('8度的破坏占比不为100')
    }
    if (precision(five, 3) != 100||precision(five, 3) != 100.0||precision(five, 3) != 100.00) {
        messageArr.value.push('9度的破坏占比不为100')
    }
	if (precision(six, 3) != 100||precision(six, 3) != 100.0||precision(six, 3) != 100.00) {
        messageArr.value.push('10度的破坏占比不为100')
    }
}
const precisionTotal =(index)=>{
	let total = 0
	let obj = form.value.tableDataMatrix[index]
	total = parseFloat(obj.one)+parseFloat(obj.two)+parseFloat(obj.three)+parseFloat(obj.four)+parseFloat(obj.fiv)
	return total
}

// 设置矩阵数据
function setMatrixData(arr) {
	if (arr && arr.length) {
		// 结果列表
		const arrResult = [];
		// 烈度列表
		const arrIntensity = [];
		// 当前行数据
		let curRow = {};
		// 先按烈度排序再处理
		arr.sort((a, b) => {
			return parseInt(a.intensity) < parseInt(b.intensity) ? -1 : 1;
		}).map(item => {
			if (!arrIntensity.includes(item.intensity)) {
				arrIntensity.push(item.intensity);
				curRow = { intensity: item.intensity };
				arrResult.push(curRow);
			}
			switch (item.damage) {
				case '基本完好':
					curRow.intensity1 = item.rate;
					curRow.one = item.rate.slice(0,item.rate.length-1);
					curRow.damageBs = item.damage;
					curRow.pid = item.pid;
					break;
				case '轻微破坏':
					curRow.intensity2 = item.rate;
					curRow.two = item.rate.slice(0,item.rate.length-1);
					curRow.damageSl = item.damage;
					curRow.pid = item.pid;
					break;
				case '中等破坏':
					curRow.intensity3 = item.rate;
					curRow.three = item.rate.slice(0,item.rate.length-1);
					curRow.damageMl = item.damage;
					curRow.pid = item.pid;
					break;
				case '严重破坏':
					curRow.intensity4 = item.rate;
					curRow.four = item.rate.slice(0,item.rate.length-1);
					curRow.damageEl = item.damage;
					curRow.pid = item.pid;
					break;
				case '倒塌':
					curRow.intensity5 = item.rate;
					curRow.fiv = item.rate.slice(0,item.rate.length-1);
					curRow.damageC = item.damage;
					break;
				default:
					break;
			}
		})
		tableDataMatrix.value = arrResult;
	} else {
		tableDataMatrix.value = [];
	}
}

// 导出矩阵列表数据
function exportMatrixTableData() {
	if (tableDataMatrix.value && tableDataMatrix.value.length) {
		// 设置导出数据格式并导出
		const arrData = [];
		tableDataMatrix.value.map(item => {
			arrData.push([item.intensity, item.intensity1, item.intensity2, item.intensity3, item.intensity4, item.intensity5]);
		});
		export_json_to_excel({
			// 表头
			header: ['烈度', '基本完好', '轻微破坏', '中等破坏', '严重破坏', '倒塌'],
			data: arrData,
			filename: '易损性矩阵数据', //文件名
			autoWidth: true,
			bookType: 'xlsx',
		});
	} else {
		proxy.$modal.msgWarning('没有矩阵数据，无法导出！');
	}
}
// 生成数据
const createSuccess = (data) => {
	getList();
	onClickNumber({ id: data })
}
// 选择省
const chooseProvince = (value) => {
	queryParams.value.cityId = null
	queryParams.value.countyId = null
	queryParams.value.city = null
	queryParams.value.county = null
	cityData.value = []
	areaData.value = []
	queryParams.value.province = provinceData.value.find(item => item.id == value)?.name
	getChildArea(value).then(response => {
		cityData.value = response.data
	})
}
// 选择市
const chooseCity = (value) => {
	queryParams.value.countyId = null
	queryParams.value.county = null
	areaData.value = []
	queryParams.value.city = cityData.value.find(item => item.id == value)?.name
	getChildArea(value).then(response => {
		areaData.value = response.data
	})
}
// 选择区县
const chooseCounty = (value) => {
	queryParams.value.county = areaData.value.find(item => item.id == value)?.name
}

// 获取数据列表
const getList = () => {
	if (queryParams.value.structureType1 == 'czghjggw' && !queryParams.value.numberOfFloors) {
		proxy.$modal.msgWarning('请选择层数！')
		return
	}
	loading.value = true
	getPage({ ...queryParams.value, ysxType: radio.value }).then(res => {
		dataList.value = res.data.rows
		total.value = res.data.total
		loading.value = false
	}).catch(err => {
		dataList.value = [];
		total.value = 0;
		loading.value = false;
	})
}
// 重置查询表单
const resetQuery = () => {
	queryParams.value.page = 1
	proxy.resetForm('queryRef')
	queryParams.value.provinceId = isProvince.value ? roleObj.value.provinceId : '';
	queryParams.value.cityId = isCity.value ? roleObj.value.cityId : '';
	queryParams.value.countyId = isCounty.value ? roleObj.value.countyId : '';
	if (!isProvince.value) queryParams.value.province = '';
	if (!isCity.value) queryParams.value.city = '';
	if (!isCounty.value) queryParams.value.county = '';
	queryParams.value.structureType2 = ''
	queryParams.value.housingUse2 = ''
	queryParams.value.endTime = ''
	showMatrix.value = false;
	tableDataMatrix.value = []
	getAdmin()
	// getList()
}
// 生成弹框是否显示
const openCreat = ref(false);

// 导入弹框是否显示
let importOpen = ref(false);
const importExcel = () => {
	importOpen.value = true;
}
// 导入组件参数
const uploadParams = ref({
	url: ``,
	templateName: '易损性矩阵完全版导入模版.xlsx',
	templateUrl: '/base/product/downloadExcel',
	params: {},
	downloadParams: {fileName: '易损性矩阵完全版导入模版.xlsx'}
})
watch(() => radio.value, async () => {
	uploadParams.value.templateName = radio.value == '1' ? '易损性矩阵完全版导入模版.xlsx' : '易损性矩阵群体版导入模版.xlsx';
	uploadParams.value.url = `/jzwysx/uploadYsxExcel?jsxType=${radio.value}&province=${queryParams.value.province}&city=${queryParams.value.city}&county=${queryParams.value.county}&roleType=${queryParams.value.roleType}`
	uploadParams.value.downloadParams.fileName = uploadParams.value.templateName;
}, { immediate: true, deep: true })
// 导入成功回调
const importSuccess = () => {
	proxy.$modal.msgSuccess('导入数据成功!');
	// 关闭弹框
	importOpen.value = false;
	// 获取数据列表
	getList();
}
// 倒入覆盖
const importCover = () => {
	proxy.$modal.msgSuccess('导入数据并成功覆盖!');
	// 关闭弹框
	importOpen.value = false;
	// 获取数据列表
	getList();
}
const creatOpen = () =>{
	openCreat.value = true;
	nextTick(() => {
  	  proxy.$refs["creatDataRef"].reset();
  	});
}
// 维护时间可选范围控制
const startDisableDate = (time) => {
	let endDateVal = queryParams.value.endTime;
	if (endDateVal) {
		return time.getTime() > new Date(endDateVal).getTime();
	}
};
const endDisableDate = (time) => {
	let beginDateVal = queryParams.value.startTime;
	if (beginDateVal) {
		return time.getTime() < new Date(beginDateVal).getTime();
	}
};
// 获取权限
const isProvince = ref(false);
const isCity = ref(false);
const isCounty = ref(false);
const roleObj = {};
const getAdmin = async () => {
	let res = await getProvince()
	if (res.code == 200) {
		provinceData.value = res.data
	}
	getRole().then(res => {
		const { code, data } = res;
		if (code == 200) {
			roleObj.value = data;
			const role = data.role
			switch (role) {
				case 'qh_gj_role': // 国家级
					isProvince.value = false;
					isCity.value = false;
					isCounty.value = false;
					queryParams.value.provinceId = provinceData.value.find(item => item.name == '北京市')?.id;// 默认传北京市
					getChildArea(queryParams.value.provinceId).then(response => {
						cityData.value = response.data;
					})
					queryParams.value.cityId = '';
					queryParams.value.countyId = '';
					queryParams.value.province = '北京市';
					queryParams.value.city = '';
					queryParams.value.county = '';
					queryParams.value.roleType = '0'
					getList()
					break;
				case 'qh_province_role': // 省级
					isProvince.value = true;
					queryParams.value.provinceId = data.provinceId;
					getChildArea(queryParams.value.provinceId).then(response => {
						cityData.value = response.data;
					})
					queryParams.value.province = provinceData.value.find(item => item.id == data.provinceId)?.name
					isCity.value = false;
					isCounty.value = false;
					queryParams.value.roleType = '1'
					getList()
					break;
				case 'qh_city_role':
					isProvince.value = true; // 市级
					isCity.value = true;
					queryParams.value.provinceId = data.provinceId;
					queryParams.value.cityId = data.cityId;
					isCounty.value = false;
					queryParams.value.roleType = '2'
					getChildArea(queryParams.value.provinceId).then(response => {
						cityData.value = response.data;
						queryParams.value.province = provinceData.value.find(item => item.id == data.provinceId)?.name;
						queryParams.value.city = cityData.value.find(item => item.id == data.cityId)?.name
						chooseCity(data.cityId)
						getList()
					})
					break;
				case 'ph_county_role':
					isProvince.value = true; // 县级
					isCity.value = true;
					isCounty.value = true;
					queryParams.value.provinceId = data.provinceId;
					queryParams.value.cityId = data.cityId;
					queryParams.value.countyId = data.countyId;
					queryParams.value.roleType = '3'
					getChildArea(queryParams.value.provinceId).then(response => {
						cityData.value = response.data;
						getChildArea(queryParams.value.cityId).then(response => {
							areaData.value = response.data;
							queryParams.value.province = provinceData.value.find(item => item.id == data.provinceId)?.name
							queryParams.value.city = cityData.value.find(item => item.id == data.cityId)?.name
							queryParams.value.county = areaData.value.find(item => item.id == data.countyId)?.name
							getList();
						})
					})
					break;
				default:
					break;
			}
		}
	})
}

// 公里格网

const selectedName = ref('first')
const tabClick = () =>{
	if(selectedName.value=='first'){
		getAdmin();
	}else{

	}
}
// 挂载
onMounted(() => {
	if(selectedName.value=='first'){
		getAdmin();
	}
})
</script>

<style scoped lang="scss">
.table-matrix {
	margin-top: 18px;
}
:deep(.listTables){
	thead.is-group tr:last-of-type th:first-of-type:before {
    content: "";
    position: absolute;
    width: 0.5px;
    height: 180px;
    bottom: 0px;
    right: 0;
    background-color: #fff !important;
    display: block;
    transform: rotate(-59deg);
    transform-origin: bottom;
  }
	thead.is-group tr:last-of-type th:first-of-type>.cell{
		text-align: left;
	}
	thead.is-group tr:first-of-type th:first-of-type {
		border-bottom: none!important;
	}
}
</style>